package com.example.pixelyear.utils

import android.content.Context
import android.os.Build
import android.os.Environment
import com.example.pixelyear.Interface.OnDownloadCancelListener
import com.example.pixelyear.Interface.OnOssDownloadListener
import com.example.pixelyear.Interface.OnOssRestoreListener
import com.example.pixelyear.MyApp
import com.example.pixelyear.bean.VersionBean
import com.example.pixelyear.ui.base.BaseActivity
import com.example.pixelyear.utils.dialog.ProgressDialog
import com.example.pixelyear.utils.extension.RefreshPhotos
import com.example.pixelyear.utils.oss.NetBackBackUpUtils
import com.socks.library.KLog
import org.jetbrains.anko.runOnUiThread
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.net.URL
import kotlin.concurrent.thread

object FunctionUtils {

    //获取服务器时间与本地时间差
    fun checkServiceTime(context: Context) {
        if (Utils.getNetState(context) != Utils.NETWORK_NONE) {
            thread {
                val url = URL("http://www.baidu.com")//取得资源对象
                val uc = url.openConnection()//生成连接对象
                uc.connect() //发出连接
                val ld = uc.date //取得网站日期时间
                val systemTime = System.currentTimeMillis()
                YxsSpUtils.putLong(Constant.NOW_TIME, systemTime - ld)
                if (YxsSpUtils.getInt(Constant.FIRST_ENTER_APP_YEAR, 0) == 0)
                    YxsSpUtils.putInt(Constant.FIRST_ENTER_APP_YEAR, Utils.getYear())

                if (YxsSpUtils.getInt(Constant.FIRST_ENTER_APP_MONTH, 0) == 0)
                    YxsSpUtils.putInt(Constant.FIRST_ENTER_APP_MONTH, Utils.getMonth())
            }
        }

    }


    fun getPhoneImei(context: Context): String {
        return if (YxsSpUtils.getString(Constant.PHONE_IMEI).isEmpty()) {
            Utils.getPhoneIMEI(context).also {
                YxsSpUtils.putString(Constant.PHONE_IMEI, it)
            }
        } else YxsSpUtils.getString(Constant.PHONE_IMEI)
    }


    //获取下载地址适配Android Q
    fun getDownloadAddressForAndroidVersion(context: Context, type: String = ""): String {
        return if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P)
            context.getExternalFilesDir(if (type.isEmpty()) Environment.DIRECTORY_DOWNLOADS else type)?.absolutePath
                ?: ""
        else {
            File(Environment.getExternalStorageDirectory().absolutePath + "/${context.packageName}").also {
                if (!it.exists())
                    it.mkdir()
            }.path
        }
    }


    fun checkUpdate(context: BaseActivity, update: (apk: String) -> Unit) {
        val ossUtils = NetBackBackUpUtils.getInstance(context)
        val versionText = if (MyApp.isDebug()) "version_test.txt" else "version.txt"
        if (ossUtils.checkFileExists(versionText)) {
            ossUtils.restore(versionText, object : OnOssRestoreListener {
                override fun onSuccess(stream: InputStream) {
                    val parsingInput = Utils.parsingInput(stream)
                    KLog.e("yxs", "返回的数据：$parsingInput")
                    val bean = VersionBean.objectFromData(parsingInput)
                    loadSplash(context, ossUtils, bean.splash)
                    if (Utils.getVersionName(context) != bean.version && versionContrast(bean.version) > 0) {
                        context.runOnUiThread {
                            TipsDialogUtils.showSureCancelDialog(
                                context,
                                okText = "立即更新",
                                content = bean.msg
                            ) {
                                update.invoke(bean.apk)
                            }
                        }
                    } else {
                        if (bean.showDialog != null) {
                            if (bean.showDialog.isBan_cancel) {
                                showBanCancelDialog(context, bean = bean.showDialog)
                            } else {
                                if (bean.showDialog.code == -1) {
                                    val number = YxsSpUtils.getInt(Constant.DIALOG_SHOW_NUMBER, 1)
                                    if (number <= 3) {
                                        showBanCancelDialog(context, bean = bean.showDialog)
                                        YxsSpUtils.putInt(Constant.DIALOG_SHOW_NUMBER, number + 1)
                                    }
                                } else {
                                    if (YxsSpUtils.getInt(Constant.DIALOG_CODE) != bean.showDialog.code) {
                                        YxsSpUtils.putInt(
                                            Constant.DIALOG_CODE,
                                            bean.showDialog.code
                                        )
                                        showBanCancelDialog(context, bean = bean.showDialog)
                                        YxsSpUtils.remove(Constant.DIALOG_SHOW_NUMBER)
                                    }
                                }
                            }
                        }
                    }
                }

                override fun onFailure() {

                }
            })

        }
    }

    fun downloadApk(context: Context, apk: String) {
        val ossUtils = NetBackBackUpUtils.getInstance(context)
        if (!ossUtils.checkFileExists(apk)) {
            Utils.showToast("出现了未知错误，请联系程序猿！")
            return
        }
        val dialog = ProgressDialog(context)
        dialog.show()
        val download = ossUtils.download(apk, object : OnOssDownloadListener {
            override fun progress(size: Long, current: Long) {
                context.runOnUiThread {
                    dialog.updateProgress(((current.toFloat() / size.toFloat()) * 100).toInt())
                }
            }

            override fun onSuccess(stream: InputStream) {
                val file = File(getDownloadAddressForAndroidVersion(context))
                if (!file.exists())
                    file.mkdirs()
                val apkFile = File(file, apk)
                Utils.copy(stream, apkFile)
                context.runOnUiThread {
                    dialog.dismiss()
                    InstallUtils.Install(context, apkFile)
                }


            }

            override fun onFailure() {
                context.runOnUiThread {
                    dialog.dismiss()
                }
            }
        })

        dialog.setOnProgressCancelListener(OnDownloadCancelListener {
            download.cancel()
            dialog.dismiss()
        })

    }

    private fun showBanCancelDialog(context: BaseActivity, bean: VersionBean.ShowDialogBean) {
        context.runOnUiThread {
            TipsDialogUtils.showBanCancelDialog(
                context,
                content = bean.dialog_msg,
                okText = if (bean.isBan_cancel) "关闭App" else "确定",
                cancelText = "",
                banCancel = bean.isBan_cancel
            ) {
                context.finish()
            }
        }
    }

    private fun loadSplash(context: Context, ossUtils: NetBackBackUpUtils, img: String) {
        if (YxsSpUtils.getBoolean(Constant.SD) && img.isNotEmpty() && ossUtils.checkFileExists(img)) {
            val imgFile = File(getDownloadAddressForAndroidVersion(context) + "/$img")
            if (!imgFile.exists()) {
                ossUtils.restore(img, object : OnOssRestoreListener {
                    override fun onSuccess(stream: InputStream) {
                        YxsSpUtils.putString(Constant.SPLASH_IMG, imgFile.path)
                        Utils.copy(stream, imgFile)
                    }

                    override fun onFailure() {
                        YxsSpUtils.remove(Constant.SPLASH_IMG)
                    }
                })
            }
        }
    }


    //复制dat文件到SD卡
    fun copyQrCodeToSD(context: Context, have: () -> Unit) {
        val oldFile = File(Environment.getExternalStorageDirectory().absolutePath + "/qr")
        if (!oldFile.exists())
            oldFile.mkdirs()
        val file = File(oldFile, "pay_qr_code.jpg")
        if (!file.exists()) {
            try {
                val open = context.assets.open("pay_qr_code.jpg")
                Utils.copy(open, file)
                RefreshPhotos(context, file)
                Utils.showToast("不错，年轻人，我看好你，我的收款码已放到你的相册～")
            } catch (e: IOException) {
                e.printStackTrace()
            }
        } else have.invoke()
    }

    /**
     * 比较新版本和老版本之间相差了几个版本
     */
    fun versionContrast(string: String): Int {
        val newVersion = string.split(".")
            .let { if (it.isEmpty() || it.size != 3) -1 else (it[it.size - 1].toInt()) + (it[it.size - 2].toInt() * 10) + (it[it.size - 3].toInt() * 100) }
        val nowVersion = Utils.getVersionName(MyApp.getContext()).split(".")
            .let { if (it.isEmpty() || it.size != 3) -1 else (it[it.size - 1].toInt()) + (it[it.size - 2].toInt() * 10) + (it[it.size - 3].toInt() * 100) }
        if (newVersion == -1 || nowVersion == -1) return -1
        return newVersion - nowVersion
    }

}
